package training.sample.app.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import training.sample.app.domain.UserAccount;
import training.sample.app.service.UserService;

@Controller
@RequestMapping("")
public class LoginController {

	@Autowired
	private UserService userService;
	
	@PreAuthorize("permitAll")
	@RequestMapping(value = { "", "/", "/login" }, method = { RequestMethod.GET })
	public ModelAndView login(HttpSession session,
		@RequestParam(value = "logout", required = false) String logout) {
 
		ModelAndView model = new ModelAndView();
		model.setViewName("login");
		
		if (logout != null) {
			model.addObject("msg", "You've been logged out successfully.");
			session.invalidate();
		} else if (isUserSessionFound(session)) {
			model.setViewName("profile");
		}
		
		return model;
	}
	
	@RequestMapping(value = "/access-denied")
	public String accessDenied(HttpSession session) {
		return "access-denied";
	}
	
	private boolean isUserSessionFound(HttpSession session) {
		return session.getAttribute("user") instanceof UserAccount;
	}
	
	
	
	
	
	
	

	// The method is not currently in use
	// Logging in is handled by Spring Security
	@PreAuthorize("isAnonymous()")
	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public ModelAndView login(
		@RequestParam(value = "username", required = true) String username,
		@RequestParam(value = "password", required = true) String password,
		HttpServletRequest request, HttpSession session) {
		
		ModelAndView mav = new ModelAndView();

		//String password = "psswd"; 
		//PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); 
		//String encodedPassword = passwordEncoder.encode(password); 
		
		UserAccount user = userService.loadUserByCredentials(username, password);
		if (user != null) {
			session.setAttribute("user", user);
			mav = new ModelAndView("redirect:/profile/"+user.getUserId());
			mav.addObject("user.name", user.getName());
		} else {
			mav.addObject("error", "Invalid username or password!");
			mav.setViewName("login");
		}
 
		return mav;
	}
	
	// The method is not currently in use
	// Logging in is handled by Spring Security
	@RequestMapping(value = "/logout")
	public ModelAndView logout(HttpSession session) {

		ModelAndView model = new ModelAndView();
		model.setViewName("login");
		
		session.setAttribute("user", null);
		session.invalidate();
		
		return model;
	}
}